/**
 * 加班记录
 */
import React, { useEffect, useRef } from 'react';
import { connect } from 'umi';
import { router, Link } from 'umi';
import { Form, Input, Button, Table, Card } from 'antd';
import moment from 'moment';
import cn from 'classnames';
import { get as getPath } from 'object-path';

import { QuickForm, utils } from 'vv-frontend-components';
import Locale from '@/utils/locale';
// import request from '@/utils/request';
import { dateConversion2, download } from '@/utils/utils';
import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import { withRoutePage } from '@/utils/enhanceUtils';
import DateRange from '@/components/DateRange';
import CompanyDepartPlus from '@/containers/select/CompanyDepartPlus';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
// import TableFilter from '@/components/TableFilter';
import LinkTo from '@/components/LinkTo';
import { Pagination } from '@/components';
import styles from './index.less';
import BuLuForm from './BuLuForm';

const { locale } = new Locale('stat.overtime');
const { deepTrim } = utils;
const ButtonContainer = ({ children, style }) => (
    <div style={{ ...style }} className={styles.buttonContainer}>
        {children}
    </div>
);
const ORDER_MAP = {
    'apply_start_time asc': 'ascend',
    'apply_start_time desc': 'descend',
    'start_time asc': 'ascend',
    'start_time desc': 'descend',
    'over_long asc': 'ascend',
    'over_long desc': 'descend'
};

const toArray = input => {
    if (!input) return [];
    if (Array.isArray(input)) return input;
    return [input];
};

const List = ({ form, loading, dispatch, route, location, overbusinessrecords }) => {
    const { getFieldsValue } = form;
    const { authCode } = new AuthCode(route.code);
    const refFrom = useRef(null);
    const { query } = location;
    const { quarter } = query;

    const { typeList, overtimeList: data, Isovertime, overtimePagination } = overbusinessrecords;

    const { total = 0 } = overtimePagination || {};

    const dictColor = {
        0: '#52C41A',
        1: 'rgba(0,0,0,0.65)',
        2: '#F5222D'
    };

    const getParams = (extra = {}) => {
        const { companyDepart, userName, date } = getFieldsValue();
        const { overSign, overStatus, pageNo, pageSize, orderByField } = query;

        return {
            companyCode: companyDepart?.companyId || '',
            departmentCode: companyDepart?.departmentId || '',
            startTime: date?.range[0] ? date.range[0].format('YYYY-MM-DD') : '',
            endTime: date?.range[1] ? date.range[1].format('YYYY-MM-DD') : '',
            employeeName: userName || '',
            overSign: toArray(overSign),
            overStatus: toArray(overStatus),
            pageNo,
            pageSize,
            orderByField,
            dateType: date?.type,
            ...extra
        };
    };

    const fetchList = extra => {
        dispatch({
            type: 'overbusinessrecords/fetchOvertimeList',
            payload: getParams(extra)
        });
    };

    // 搜索表单写入query
    const applyToQuery = (extra = {}) => {
        history.push({
            query: {
                ...query,
                ...getParams(),
                ...extra
            }
        });
    };

    useEffect(() => {
        fetchList();
    }, [JSON.stringify(query)]);

    useEffect(() => {
        dispatch({
            type: 'overbusinessrecords/fetchTypeList',
            payload: {
                dictCode: 'overtimeSign'
            }
        });
        dispatch({
            type: 'overbusinessrecords/fetchIsovertimeList',
            payload: {
                dictCode: 'overtimeStatus'
            }
        });
    }, []);

    const handleExport = async () => {
        const { pageNo, pageSize, ...other } = getParams();
        download({
            getData: () =>
                dispatch({
                    type: 'overbusinessrecords/fetchOverTimeExport',
                    payload: deepTrim(other)
                })
        });
    };

    // query中的初始值
    const {
        companyCode: companyId,
        departmentCode: departmentId,
        startTime,
        endTime,
        employeeName,
        orderByField,
        overSign,
        overStatus,
        dateType
    } = query;

    const initCompanyDepart = companyId || departmentId ? { companyId, departmentId } : undefined;

    const config = [
        {
            field: 'companyDepart',
            label: '机构',
            config: {
                initialValue: initCompanyDepart
            },
            component: <CompanyDepartPlus />
        },
        {
            field: 'userName',
            label: '员工',
            config: {
                initialValue: employeeName
            },
            component: <Input placeholder="输入姓名" />
        },
        {
            field: 'date',
            config: {
                initialValue: {
                    range: [
                        typeof startTime === 'undefined' ? moment().startOf('month') : moment(startTime),
                        typeof endTime === 'undefined' ? moment() : moment(endTime)
                    ],
                    quarter: quarter ? Number(quarter) : 1,
                    type: typeof dateType === 'undefined' ? 'month' : dateType
                }
            },
            component: (
                <DateRange
                    range
                    dateTypes={[
                        {
                            label: '本周',
                            type: 'week'
                        },
                        {
                            label: '本月',
                            type: 'month'
                        },
                        {
                            label: '本年',
                            type: 'year'
                        }
                    ]}
                />
            )
        },
        {
            component: (
                <ButtonContainer>
                    <Button type="primary" htmlType="submit">
                        {locale('form.search', false)}
                    </Button>
                    <AuthComponent code={authCode('export')}>
                        <Button
                            onClick={handleExport}
                            loading={loading.effects['overbusinessrecords/fetchOvertimeList']}
                        >
                            导出
                        </Button>
                    </AuthComponent>
                    <AuthComponent code={authCode('manual')}>
                        <Button onClick={() => refFrom.current.show()}>手动补录</Button>
                    </AuthComponent>
                </ButtonContainer>
            )
        }
    ];

    const transformSortOrder = currentField => {
        if (!orderByField) return false;
        const [field = ''] = orderByField.split(' ');
        if (field !== currentField) {
            return false;
        }
        return ORDER_MAP[orderByField];
    };

    const columns = [
        {
            title: '工号',
            dataIndex: 'userNo',
            key: 'userNo'
        },
        {
            title: '姓名',
            dataIndex: 'userName',
            key: 'userName',
            width: 90
        },
        {
            title: '组织机构',
            dataIndex: 'departName',
            key: 'departName',
            render: text => (
                <div className={styles.ellipsis} title={text}>
                    {text}
                </div>
            )
        },
        {
            title: '加班类型',
            dataIndex: 'overtimeSign',
            key: 'overtimeSign',
            filters: typeList || [],
            width: 150,
            filteredValue: toArray(overSign),
            // filterDropdown: filterProps => <TableFilter {...filterProps} />,
            // filterMultiple: false,
            render(text, record) {
                return <span>{record.overtimeSignNick}</span>;
            }
        },
        {
            title: '申请加班时间',
            dataIndex: 'applyTime',
            key: 'applyTime',
            width: 200,
            sortOrder: transformSortOrder('apply_start_time'),
            sorter: true,
            render(text, record) {
                if (record.applyStartTime === '') {
                    return <span>--</span>;
                }
                return (
                    <span>
                        {record.applyStartTime}
                        <br />
                        {record.applyEndTime}
                    </span>
                );
            }
        },
        {
            title: '是否加班',
            dataIndex: 'status',
            key: 'status',
            width: 150,
            filters: Isovertime || [],
            filteredValue: toArray(overStatus),
            // filterDropdown: filterProps => <TableFilter {...filterProps} />,
            // filterMultiple: false,
            render(text, record) {
                return <span style={{ color: dictColor[text] }}>{record.statusNick}</span>;
            }
        },
        {
            title: '实际加班时间',
            dataIndex: 'Time',
            key: 'Time',
            width: 200,
            sortOrder: transformSortOrder('start_time'),
            sorter: true,
            render(text, record) {
                const nodeHasTime = (
                    <span>
                        {record.startTime}
                        <br />
                        {record.endTime}
                    </span>
                );
                return (
                    <div>
                        {record.startTime && record.status && record.status === 1 ? nodeHasTime : <span>--</span>}
                    </div>
                );
            }
        },
        {
            title: '时长',
            dataIndex: 'overLong',
            key: 'overLong',
            width: 150,
            sortOrder: transformSortOrder('over_long'),
            sorter: true,
            render: (text, record) => (
                <div>
                    {record.startTime && record.status && record.status === 1 ? (
                        <span>{dateConversion2(text)}</span>
                    ) : (
                        <span>--</span>
                    )}
                </div>
            )
        },
        {
            title: '相关流程',
            dataIndex: 'applicationNo',
            key: 'applicationNo',
            width: 200,
            render(text, record) {
                const { applicationNo, remark = '' } = record;
                const flag = remark === 'hide';
                const isOldFlow = !applicationNo.includes('-');
                const url = isOldFlow
                    ? '/office/institutions/flowManage/fullApprovalProcess/processDetail'
                    : '/personal/portal/myAuditRead/myAuditReadDetail';
                const params = isOldFlow ? { applicationNo, linkFrom: '1' } : { applicationNo };
                return (
                    <span>
                        {text === '' ? (
                            '--'
                        ) : (
                            <LinkTo to={url} query={params} className={cn({ [styles.disabled]: flag })}>
                                {text}
                            </LinkTo>
                        )}
                    </span>
                );
            }
        },
        {
            title: '操作',
            dataIndex: 'actionLink',
            key: 'actionLink',
            width: 100,
            fixed: 'right',
            render(text, record) {
                return record.status === 0 || record.applicationNo === '' ? (
                    '--'
                ) : (
                    <Link
                        to={{
                            pathname: '/office/personnelManagement/attendance/timetag/attendRecord/clockRecord',
                            query: {
                                id: record.employeeCode,
                                name: record.userName,
                                startTime: record.applyStartTime,
                                endTime: record.applyEndTime
                            }
                        }}
                    >
                        打卡记录
                    </Link>
                );
            }
        }
    ];

    const tableChange = (newPagination, filters, sorters) => {
        const pagination = {
            current: query.pageSize,
            pageSize: query.pageSize
        };

        let orderBy;
        let sorterField;
        let nextQuery = {
            ...pagination,
            ...newPagination
        };
        if (filters && Object.keys(filters).length) {
            nextQuery = {
                ...nextQuery,
                overSign: getPath(filters, 'overtimeSign', []),
                overStatus: getPath(filters, 'status', [])
            };
        }
        if (sorters) {
            const returnOrderBy = s => {
                if (s.field === 'applyTime') {
                    sorterField = 'apply_start_time';
                }
                if (s.field === 'Time') {
                    sorterField = 'start_time';
                }
                if (s.field === 'overLong') {
                    sorterField = 'over_long';
                }
                orderBy = `${sorterField} ${s.order.replace('end', '')}`;
            };
            if (sorters && sorters.field && sorters.order) {
                returnOrderBy(sorters);
            } else if (typeof sorters === 'string') {
                orderBy = '';
            }
            nextQuery = {
                ...nextQuery,
                orderByField: orderBy
            };
        }
        applyToQuery({ ...nextQuery, pageNo: 1 });
    };

    const handlePaginationChange = pagination => {
        const { current, pageSize } = pagination;
        history.push({ query: { ...query, pageNo: current, pageSize } });
    };

    return (
        <PageHeaderWrapper>
            <Card>
                <Form
                    layout="inline"
                    style={{ marginBottom: 15 }}
                    onSubmit={e => {
                        e.preventDefault();
                        const extra = { pageNo: 1 };
                        fetchList(extra);
                        applyToQuery(extra);
                    }}
                >
                    <QuickForm form={form} config={config} />
                </Form>
                <Table
                    bordered={false}
                    columns={columns}
                    loading={loading.models.overbusinessrecords}
                    dataSource={data}
                    rowKey="id"
                    onChange={tableChange}
                    pagination={false}
                    scroll={{ x: 'max-content' }}
                />
                <Pagination
                    total={total}
                    onChange={handlePaginationChange}
                    current={query.pageNo || 1}
                    pageSize={query.pageSize || 10}
                    loading={loading.models.overbusinessrecords}
                />
                <BuLuForm wrappedComponentRef={refFrom} callBack={() => fetchList({ pageNo: 1 })} />
            </Card>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(
    connect(({ overbusinessrecords, loading }) => ({ overbusinessrecords, loading }))(Form.create()(List))
);
